<?php
/*User tracking functions included in Securesite plugin.  modified to include feed use tracking
 * with feed keys
 */
/* ORIGINAL PLUGIN INFO - UserTracker by Chris Black, version 1.2, http://cjbonline.org
*
*/


$myTableName = $wpdb->prefix . 'usertracker';

function UT_add_pages() {
        add_submenu_page('index.php', __('UT Stats'), __('UT Stats'), 'manage_categories', 'securesite-track', 'UT_statsPage');
}

function UT_userLogin($userLogin) {
	$userdata = get_userdatabylogin($userLogin);
	update_usermeta($userdata->ID,'lastLogin',date('m-d-Y G:i:s'));
	return $userLogin;
}

function UT_trackUser($postid = 0) {
	global $userdata, $wpdb, $myTableName, $post;
	
        //Only saved page redirects or single post pages
        
	if ($postid == 0 && !is_single()) {
		return true;
	}
	$myDB = $wpdb;
	//get_currentuserinfo();

	if ($_SERVER['SCRIPT_URI'] != '') {
		$myPage = $_SERVER['SCRIPT_URI'];
	} else if ($_SERVER['REQUEST_URI'] != '') {
		$myPage = $_SERVER['REQUEST_URI'];
	} else {
		$myPage = $_SERVER['SCRIPT_NAME'];
	}
        if (is_single()){
            $postid = $post->ID;
            $transid = get_transient('mct_st_doublecnt');  //need to skip multiple calls to wp_head hook
            if ($transid == $postid) return;
            set_transient('mct_st_doublecnt',$postid,2);
        } 
        if ($userdata->ID != '') {
		$sql = "INSERT INTO " . $myTableName . " (date,user_id,url,title,referer,user_agent,ip, post_id) 
                    VALUES (NOW()," . $userdata->ID . ",'" . $myPage . "','','" . $_SERVER['HTTP_REFERER'] . "','"
                        . $_SERVER['HTTP_USER_AGENT'] . "','" . $_SERVER['REMOTE_ADDR'] . "', '$postid')";
		$myDB->query($sql);
	}
}

function UT_trackGuest($postid = 0) {
	global $userdata, $wpdb, $myTableName, $post;
	
        //Only saved page redirects or single post pages
        
	if ($postid == 0 && !is_singular()) {
		return true;
	}
        //Skip bots, spyders
        $uagnt = $_SERVER['HTTP_USER_AGENT'];
        if (stripos($uagnt, 'bot') !== false) return;
	if (stripos($uagnt, 'spider') !== false) return;
        
        $myDB = $wpdb;
	//get_currentuserinfo();

	if ($_SERVER['SCRIPT_URI'] != '') {
		$myPage = $_SERVER['SCRIPT_URI'];
	} else if ($_SERVER['REQUEST_URI'] != '') {
		$myPage = $_SERVER['REQUEST_URI'];
	} else {
		$myPage = $_SERVER['SCRIPT_NAME'];
	}
        if (is_singular()){
            $postid = $post->ID;
            $transid = get_transient('mct_st_doublecnt');  //need to skip multiple calls to wp_head hook
            if ($transid == $postid) return;
            set_transient('mct_st_doublecnt',$postid,2);
        } 
        if ($userdata->ID != '') { 
            $usr = $userdata->ID;
        } else {
            $usr = 0;
        }
        
        $ptype = get_post_type($postid);
        if ($ptype != 'post' && $ptype != 'page') return;
        $sql = "INSERT INTO " . $myTableName . " (date,user_id,url,title,referer,user_agent,ip, post_id) 
                    VALUES (NOW(), '".$usr."','" . $myPage . "','','" . $_SERVER['HTTP_REFERER'] . "','"
                        . $_SERVER['HTTP_USER_AGENT'] . "','" . $_SERVER['REMOTE_ADDR'] . "', '$postid')";
	$myDB->query($sql);
	
}
function UT_trackFeed($UsrID) {
	global $wpdb, $myTableName, $members_only_opt;
	
        if ($members_only_opt['UT_trackon'] == FALSE){
            return;
        }
	$myDB = $wpdb;

	if ($_SERVER['SCRIPT_URI'] != '') {
		$myPage = $_SERVER['SCRIPT_URI'];
	} else if ($_SERVER['REQUEST_URI'] != '') {
		$myPage = $_SERVER['REQUEST_URI'];
	} else {
		$myPage = $_SERVER['SCRIPT_NAME'];
	}
	
	if ($UsrID != '') {
		$sql = "INSERT INTO " . $myTableName . " (date,user_id,url,title,referer,user_agent,ip) VALUES (NOW()," . $UsrID . ",'" . $myPage . "','','" . $_SERVER['HTTP_REFERER'] . "','" . $_SERVER['HTTP_USER_AGENT'] . "','" . $_SERVER['REMOTE_ADDR'] . "')";
		$myDB->query($sql);
	}
}

function UT_statsPage() {
	global $wpdb, $myTableName, $members_only_opt;
        
        //Delete older records based on options, if not a post or get, then first time in
        if (!isset($_POST['submit']) && !isset($_GET['paged'])){
               $back = trim($members_only_opt['UT_back']);
               $sql = "DELETE FROM ".$myTableName. " WHERE date < ADDDATE(NOW(),-".$back.")";
               $dels = $wpdb->query($sql);
               if ($dels === FALSE) {
                   $dels = "Error";
               }
               $show_result = TRUE;
        } else {
            $show_result = FALSE;
        }
       
	if ( !isset( $_GET['paged'] ) ) {
		$_GET['paged'] = 1;
	}
	
	$currentPage = $_GET['paged'];

	if (isset($_POST['m']) && $_POST['m'] != '') {
		$selectedUser = $_POST['m'];
//		print("Post:" . $selectedUser);
	} else if (isset($_GET['m']) && $_GET['m'] != '') {
		$selectedUser = $_GET['m'];
//		print("Get:" . $selectedUser);
	} else {
		$selectedUser = '';
//		print("Else:" . $selectedUser);
	}

	
	$sql = "SELECT COUNT(*) as myCount FROM " . $myTableName . " WHERE url NOT LIKE '%adsense-track.js%'";
	if ($selectedUser != '') {
		$sql .= " AND user_id = " . $selectedUser;
	}
	
	$result = $wpdb->get_results($sql);
	foreach ($result as $count) {
		$myCount = $count->myCount;
	}
	
	print ("<div id=\"wpbody\">
	<div class=\"wrap\"><h2>User Tracker Stats</h2>");
        if ($show_result){
            print("(Removed ".$dels." old records)");
        }
	print("<br/><div class=\"tablenav\">");

	$page_links = paginate_links( array(
		'base' => add_query_arg( 'paged', '%#%' ) . "&m=$selectedUser",
		'format' => '',
		'total' => ceil($myCount/30),
		'current' => $currentPage
	));
	
	if ( $page_links )
		echo "<div class='tablenav-pages'>$page_links</div>";
	
	print("<div class=\"alignleft\"><form id=\"userTracker-filter\" action=\"" . get_bloginfo('wpurl') . "/wp-admin/admin.php?page=securesite-track\" method=\"post\">
		<select name='m'>
		<option ");
	if ($selectedUser == '') {
		print(" SELECTED ");
	}
	print("value='-1'>View all users</option>");

	$wp_user_search = new WP_User_Search();
	foreach ( $wp_user_search->get_results() as $userid ) {
		$user_object = new WP_User($userid);
		print("<option value='" . $user_object->ID. "'");
		if ($selectedUser == $user_object->ID) {
			print(" SELECTED ");
		}
		print(">" . $user_object->display_name . "");

		$sql = "SELECT COUNT(*) as myCount FROM " . $myTableName . " WHERE url NOT LIKE '%adsense-track.js%' AND user_id = " . $user_object->ID;
		$result = $wpdb->get_results($sql);
		foreach ($result as $count) {
			$myCount = $count->myCount;
		}
		print(" - $myCount </option>");

	}
		
		
	print("</select>
		
		<input type=\"submit\" name=\"submit\" id=\"post-query-submit\" value=\"Filter\" class=\"button-secondary\" />
		</form>
		</div>
		
		<br class=\"clear\" />
		</div>
		
		<br class=\"clear\" />");
	
	
	$bottom = ($currentPage - 1) * 30;
	$top = $currentPage * 30;
	$sql = "select date as mydate, url , display_name , ip , referer, user_agent, post_id, u.ID as user_id from " . $myTableName . " ut left join " . $wpdb->users . " u on u.ID =ut.user_id WHERE url NOT LIKE '%adsense-track.js%' ";
	if ($selectedUser != '' && $selectedUser != '-1') {
		$sql .= " AND u.ID = " . $selectedUser;
	}
	$sql .= " ORDER BY ut.date DESC LIMIT " . $bottom . "," . $top;
	
//	print("SQL:" . $sql);
	$result = $wpdb->get_results($sql);
	print("<table class=\"widefat\">
	<thead><tr>
		<th scope=\"col\" >Date</th>
		<th scope=\"col\" >Name</th>
		<th scope=\"col\" >URL</th>
                <th scope=\"col\" >Referrer</th>
                <th scope=\"col\" >IP Address</th>
                <th scope=\"col\" >Post</th>
	</tr></thead>");
	$alter = true;
	foreach($result as $stat) {
		print("<tr");
		
		if ($alter) {
		 	$alter = false;
		 	print(" class='alternate' ");
		} else {
			$alter = true;
		}
                $iplink = '<a href="http://whois.arin.net/rest/ip/'.strval($stat->ip).'" >'.strval($stat->ip).'</a>';
		print(">
			<td> " . $stat->mydate . "</td>
			<td> <a href=\"" . get_bloginfo('wpurl') . "/wp-admin/user-edit.php?user_id=" . $stat->user_id . "\">" . $stat->display_name . "</a></td>
			<td> <a href=\"" . $stat->url . "\" target=\"_blank\">" . $stat->url . "</a></td>
                        <td> $stat->referer </td>
                        <td> $iplink </td>
                        <td> $stat->post_id </td>
			</tr>");
	}
	print("</table></div></div>");
}

function UT_CreateTable() {
	global $wpdb, $myTableName;
        
        require_once(ABSPATH.'wp-admin/includes/upgrade.php');
        $myTableName = $wpdb->prefix . 'usertracker';
        $sql = "CREATE TABLE `$myTableName` (
            `id` BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
            `date` DATETIME NOT NULL ,
            `user_id` BIGINT(20) NOT NULL ,
            `url` VARCHAR(255) NOT NULL ,
            `title` VARCHAR(255) NOT NULL,  
            `referer` VARCHAR(255), 
            `user_agent` VARCHAR(1000), 
            `ip` VARCHAR(255),
            `post_id` INT(11) );";
	dbDelta($sql);	

}

function UT_register() {
    register_widget('UT_most_popular');
}

class UT_most_popular extends WP_Widget {
    
    function UT_most_popular() {
        $widget_ops = array (
            'classname' => 'UT_most_popular_class',
            'description' => 'Most Viewed Articles'
        );
        $this->WP_Widget('UT_most_popular', 'Most Popular', $widget_ops);
    }
    
    function widget($args,$instance){
        global $wpdb, $members_only_opt, $myTableName;
        extract ($args);

        $posts = array();
        $trans = get_transient('UT_most_popular');
        if (empty($trans)){
            //Delete old records
            $back = trim($members_only_opt['UT_back']);
            $sql = "DELETE FROM ".$myTableName. " WHERE date < ADDDATE(NOW(),-".$back.")";
            $dels = $wpdb->query($sql);
            //Get top posts
            $sql = "SELECT `post_id`, count(*)  FROM $myTableName GROUP BY `post_id` ORDER BY count(*) DESC";
            $vals = $wpdb->get_results($sql,ARRAY_A);
            if (empty($vals)) return;
            $cnt = 0;
            foreach ($vals as $val){
                if ($val['post_id'] == NULL) continue;
                $thepost = get_post($val['post_id']);
                if ($thepost->post_status != 'publish' || $thepost->post_type != 'post') continue;
                $posts[] = trim(strval($val['post_id']));
                $cnt += 1;
                if ($cnt == 3) break;
            }
            if (empty($posts)) return;
            $trans = implode(',',$posts);
            set_transient('UT_most_popular',$trans,60*60*12); //Set transient for 12 hours
        } else {
            $posts = explode(',',$trans);
        }
        
        echo $before_widget;
        //Display title
        echo $before_title."Most Popular Articles".$after_title;
        echo '<ol>';
        foreach ($posts as $postid) {
            $thepost = get_post($postid);
            $user = get_userdata($thepost->post_author);
            
            echo '<li class="cat-item" ><a href="'.get_permalink($postid).'">'.$thepost->post_title.'</a>';
            echo '&nbsp;&middot&nbsp;<em>By '.$user->user_login.'</em></li>';
        }
        //
        echo '</ol>';
       
        echo $after_widget;
    }
}
?>
